﻿#region copyright
//<copyright>
// Copyright(C) 2012 TrackerRealm Corporation
// This file is part of the open source project - Jazz. http://jazz.codeplex.com
// 
// Jazz is open software: you can redistribute it and/or modify it 
// under the terms of the GNU Affero General Public License (AGPL) as published by 
// the Free Software Foundation, version 3 of the License.
// 
// Jazz is distributed in the hope that it will be useful, 
// but WITHOUT ANY WARRANTY; without even the implied warranty 
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
//  See the GNU Affero General Public License (AGPL) for more details.
// 
// You should have received a copy of the GNU General Public 
// License along with Jazz.  If not, see <http://www.gnu.org/licenses/>.
//
// REMOVAL OF THIS NOTICE IS VIOLATION OF THE COPYRIGHT. 
//</copyright>
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Reflection;
using TrackerRealm.Jazz.Common;
using C = TrackerRealm.Jazz.Common.JazzConstants;

namespace TrackerRealm.Jazz.Client
{
    /// <summary>
    /// A '<see cref="jProfileBase"/>' instance is a collection of roles.
    /// A '<see cref="jProfileBase"/>' instance is always associated with a single '<see cref="jUserBase"/>' instance.
    /// <para>A user may have multiple 'profile's</para>
    /// </summary>
    [Jazz]
    public abstract class jProfileBase : jName, IjRoleOrProfile
    {
        /// <summary>
        /// 
        /// </summary>
        internal new readonly static jProfileBase[] EmptyArray = new jProfileBase[0];
        #region Constructors
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="name"></param>
        /// <param name="user"></param>
        /// <param name="roles"></param>
        private jProfileBase(string name, jUserBase user, IEnumerable<jRoleBase> roles)
        :this(null, name, user, roles)
        {
        }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="nexus">This object will not be 'Bound' to the Client nexus if the value is 'null'.</param>
        /// <param name="name"></param>
        /// <param name="user"></param>
        /// <param name="roles"></param>
        internal protected jProfileBase(ClientNexusBase nexus, string name, jUserBase user, IEnumerable<jRoleBase> roles)
            : base(null, name)
        {
            this._User = user;
            if(user._Profile == null) // no default profile
                user._Profile = this;
            else
                user._Profiles = user._Profiles.AddToSequence(this);
            this._ActualRoles = roles.ToArray();
            if (nexus != null)
            {
                nexus.Bind(user);
                nexus.BindIEnumerable(user._Profiles);
                user._Profiles.Foreach(p => nexus.BindIEnumerable(p.roles));
            }
        }
        #endregion
        #region User
        [BaseField]
        private jUserBase user;
        /// <summary>
        /// Returns the user for this profile.
        /// </summary>
        internal protected jUserBase _User
        {
            get { return this.user; }
            set { this.user = value; }
        }
        #endregion
        #region Profile
        /// <summary>
        /// 
        /// </summary>
        internal protected jProfileBase _Profile
        {
            get { return this; }
        }
        #endregion
        #region Roles
        [BaseField]
        private jRoleBase[] roles = jRoleBase.EmptyArray;
        /// <summary>
        /// 
        /// </summary>
        internal protected IEnumerable<jRoleBase> _Roles
        {
            get { return GetRoles(); }  
            
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        private IEnumerable<jRoleBase> GetRoles()
        {
            foreach (jRoleBase r in roles)
            {
                foreach (jRoleBase rr in r._Roles)
                {
                    yield return rr;
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        internal protected IEnumerable<jRoleBase> _ActualRoles
        {
            get { return this.roles.Select(r => r); }  //Select prevents casting to array
            set
            {
                jRoleBase[] rArray = value.ToArray();
                if (rArray.Distinct().Count() != rArray.Length)
                    throw new ArgumentException("Elements are not unique.", "value");
                if (this.IsBound)
                {
                    rArray.Where(r => !r.IsBound).Foreach(r => this.ClientNexus.Bind(r));
                    if (rArray.FirstOrDefault(r => this.ClientNexus != r.ClientNexus) != null)
                        throw new ArgumentException("Attempting to set a 'role' that is bound to another client nexus.");
                }
                this.roles = rArray;
            }
        }
        #endregion
        #region Add/Remove roles
        /// <summary>
        /// Add a role to this profile.
        /// </summary>
        /// <param name="role"></param>
        protected void _AddRole(jRoleBase role)
        {
            this._ActualRoles = this._ActualRoles.AddToUniqueSequence(role);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="role"></param>
        public void _RemoveRole(jRoleBase role)
        {
            this._ActualRoles = this._ActualRoles.RemoveFromSequence(role);
        }
        #endregion
        #region Name
        /// <summary>
        /// Returns a non unique name for this instance of a '<see cref="jObject"/>' class.
        /// <para>The returned name is the the format of 'userName.profileName'.</para>
        /// </summary>
        public override string Name
        {
            get
            {
                if (base.Name == "")
                    return this._User.Name;
                return this._User.Name + "." + base.Name;
            }
            internal protected set
            {
                if (this._User != null)
                {
                    string newName = this._User.Name + "." + value;
                    if (this._User._Profiles.FirstOrDefault(p => p.Name == newName) != null)
                    {
                        throw new ArgumentException("The profile name can not be changed. The name is used by another profile for this 'user'.", "value");
                    }
                }
                base.Name = value;
            }
        }
        #endregion


        
    }
}
